package org.jeecg.modules.netty.handler.lamp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.corp.netty.lamp.LampQueryComm;
import org.jeecg.modules.netty.CRC16Util;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class LampQueryCommToByteEncoder extends MessageToByteEncoder<LampQueryComm> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, LampQueryComm frame, ByteBuf byteBuf) throws Exception {
        List<Number> contentList = frame.getContentList();
        int len = 0;
        byte[] bytes = null;
        if(contentList!=null&&contentList.size()>0){
            bytes = content2Byte(contentList);
            len = bytes.length;
        }
        byteBuf.writeByte(frame.getMagic());
        byteBuf.writeByte(len+8);
        byteBuf.writeInt(frame.getDeviceAddr());
        byteBuf.writeBytes(bytes);

        byte[] crcBytes = new byte[byteBuf.readableBytes()];
        byteBuf.getBytes(0, crcBytes);
        int crcInt = CRC16Util.calcCrc16(crcBytes);
        log.info("crc16:{}",Integer.toHexString(crcInt));
        crcInt = CRC16Util.swapH2L(crcInt);
        byteBuf.writeShort(crcInt);
        log.info("LampQueryCommToByteEncoder执行:{}{}",CRC16Util.bytes2HexStr(crcBytes),CRC16Util.toHexStr(crcInt,false));
    }

    private static byte[] content2Byte(List<Number> contentList){
        ByteBuf buf = Unpooled.buffer(200);
        for (Number n:contentList) {
            if(n instanceof Long){
               buf.writeLong(n.longValue());
            }else if(n instanceof Integer){
                buf.writeInt(n.intValue());
            }else if(n instanceof Short){
                buf.writeShort(n.shortValue());
            }else if(n instanceof Byte){
                buf.writeByte(n.byteValue());
            }
        }
        byte[] bytes = new byte[buf.readableBytes()];
        buf.getBytes(0, bytes);
        return bytes;

    }

    public static void main(String[] args) {
        List<Number> list = new ArrayList<>();
        list.add(10L);
        list.add(5);
        list.add((short)3);
        list.add((byte)2);
        byte[] bytes = content2Byte(list);
        for (byte b:bytes) {
            System.out.print(Integer.toHexString(b)+"-");
        }
    }

}
